//
//  DateReserveTopView.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/26.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class DateReserveTopView: UIView {
    
    var selectClosure: ((_ model: DateWeekModel) -> Void)?

    @IBOutlet private weak var collectionView: UICollectionView! {
        didSet {
            collectionView.delaysContentTouches = false
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.register(DateReserveCell.nibForCell(),
                                    forCellWithReuseIdentifier: DateReserveCell.reuseIdentifier())
        }
    }
    
    private var selectedIndex = IndexPath(item: 0, section: 0)
    private var proSelectedIndex = IndexPath(item: 0, section: 0)
    
    var models = [DateWeekModel]() {
        didSet {
            collectionView.reloadData()
        }
    }
}

extension DateReserveTopView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DateReserveCell.reuseIdentifier(),
                                                      for: indexPath) as! DateReserveCell
        cell.configure(with: models[indexPath.item], indexPath: indexPath)
        if selectedIndex == indexPath {
            cell.setSelected(reset: false)
            selectClosure?(models[indexPath.item])
            proSelectedIndex = indexPath
        } else {
            cell.setSelected(reset: true)
        }
        return cell
    }
}

extension DateReserveTopView: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 58, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if selectedIndex == indexPath { return }
        selectedIndex = indexPath
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        collectionView.reloadItems(at: [selectedIndex, proSelectedIndex])
    }
}
